import { defineConfig, loadEnv } from 'vite'
import { resolve } from 'path';
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
//import windiCSS from 'vite-plugin-windicss';
import UnoCSS from 'unocss/vite'
import VueSetupExtend from 'vite-plugin-vue-setup-extend';
import AutoImport from 'unplugin-auto-import/vite';
import VueDevTools from 'vite-plugin-vue-devtools';
import Components from 'unplugin-vue-components/vite';
import { ArcoResolver  } from 'unplugin-vue-components/resolvers';
//import { createStyleImportPlugin } from 'vite-plugin-style-import';
import { vitePluginForArco } from '@arco-plugins/vite-vue'
import resolveExternalsPlugin from 'vite-plugin-resolve-externals';

export default defineConfig(({command, mode}) => {
  const env = loadEnv(mode, process.cwd());

  const {VITE_PORT, VITE_PROXY} = env;
  return {
    base: './',
    resolve: {
      alias: {
        "@": resolve(__dirname, "src"),
      },
    },
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true
        }
      }
    },
    plugins: [vue(), vueJsx(), UnoCSS(), VueSetupExtend(),
      AutoImport({
        include: [
          /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
          /\.vue$/, /\.vue\?vue/, // .vue
          /\.md$/, // .md
        ],
        imports: ['vue', 'vue-router', 'pinia'],
      }),
      //VueDevTools(),
      Components({
        include: [/\.vue$/, /\.vue\?vue/, /\.md$/,/\.jsx$/],
        resolvers: [
          ArcoResolver({
            sideEffect: true
          })
        ]
      }),
      vitePluginForArco({
        style: 'css'
      }),
      // createStyleImportPlugin({
      //   libs: [
      //     {
      //       libraryName: '@arco-design/web-vue',
      //       esModule: true,
      //       resolveStyle: (name) => {
      //         const exclude = ['menu-item','row','col','form-item','option','doption','checkbox-group','table-column','list-item',
      //         'radio-group','tab-pane']
      //         //const include = ['message',' date-picker']
      //         if(exclude.includes(name)){
      //           return ''
      //         }
      //         // less
      //         return `@arco-design/web-vue/es/${name}/style/index.js`
      //       },
      //     }
      //   ]
      // }),
      resolveExternalsPlugin({
        'mock-aws-s3': 'mock-aws-s3',
        'aws-sdk': 'aws-sdk',
        nock: 'nock',
      })
    ],
    server: {
      host: true,
      port: VITE_PORT,
      //proxy: createProxy(VITE_PROXY)
    },
  }
})

const createProxy = (proxy) => {
  const list = JSON.parse(proxy);
  const httpsRE = /^https:\/\//;
  const ret = {};
  
  for (const [prefix, target] of list) {
    const isHttps = httpsRE.test(target);

    ret[prefix] = {
      target: target,
      changeOrigin: true,
      ws: true,
      rewrite: (path) => path.replace(new RegExp(`^${prefix}`), ''),
      ...(isHttps ? { secure: false } : {}),
    };
  }
  return ret;
} 
